import AdapterUniapp from '@alova/adapter-uniapp'
import { createAlova } from 'alova'
import { mockAdapter } from './mock'

export const request = createAlova({
  baseURL: `${import.meta.env.VITE_GLOB_API_URL}${import.meta.env.VITE_GLOB_API_URL_PREFIX}`,
  timeout: 5000,
  cacheFor: null,
  ...AdapterUniapp({
    mockRequest: mockAdapter,
  }),
  responded(response) {
    const { statusCode, data } = response as UniNamespace.RequestSuccessCallbackResult
    if (statusCode >= 400) {
      throw new Error('请求错误')
    }
    return data || null
  },
  beforeRequest(method) {
    if (method.config.params) {
      const params = method.config.params
      for (const key in params) {
        if (typeof params[key] == 'object') {
          params[key] = JSON.stringify(params[key])
        }
      }
      method.config.params = params
    }
  },
})
